import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:riverpod_t/config/response_model.dart';
import 'package:riverpod_t/page/home/data/model/cartoon_model_entity.dart';
import 'package:riverpod_t/page/home/data/repository/home_repository.dart';
import 'package:riverpod_t/page/mine/state/mine_state.dart';
import 'package:riverpod_t/until/app_util.dart';
part 'mine_list_river.g.dart';

@riverpod
class MineListRiver extends _$MineListRiver {
  @override
  Future<MineState> build() async {
    return MineState(list: await _fetchAllList(1), loadFinish: true, testPage: 1);
  }

  /// 刷新方法
  void refresh({bool isRefresh = false}) async {
    try {
      state = AsyncLoading();
      int page = state.value?.page ?? 1;

      int testPage = state.value?.testPage ?? 1;
      testPage++;

      List<CartoonModelDataFeeds> list = state.value?.list ?? [];
      bool hasNext = true;
      if (isRefresh) {
        page = 1;
      } else {
        page++;
      }
      List<CartoonModelDataFeeds>? moreList = await _fetchAllList(page);
      if (AppUtil.isNotEmpty(moreList)) {
        if (isRefresh) {
          list.clear();
        }
        list.addAll(moreList);
        if (moreList.length >= 20) {
          hasNext = true;
        } else {
          hasNext = false;
        }
      } else {
        hasNext = false;
      }

      state = AsyncValue.data(
        state.value?.copyWith(
              list: list,
              page: page,
              hasNext: hasNext,
              loadFinish: true,
              testPage: testPage,
            ) ??
            MineState(list: list, loadFinish: true),
      );
    } catch (err, stack) {
      state = AsyncValue.error(err, stack);
    }
  }

  Future<List<CartoonModelDataFeeds>> _fetchAllList(int page) async {
    ResponseModel model = await HomeRepository.getListData<CartoonModelData>(page);
    CartoonModelData carDataModel = model.data;
    return carDataModel.feeds ?? [];
  }
}
